package com.shu.consumer_producer;

import java.util.LinkedList;

/**
 * @author ssm
 * @version V1.0
 * @description:
 * @date 2020/8/25 17:06
 */

public class MyBlockingQueue {

    private int maxSize;
    private LinkedList<Object> storage;

    public MyBlockingQueue(int size) {
        this.maxSize = size;
        storage = new LinkedList<>();
    }

    public synchronized void put() throws InterruptedException {
        while (storage.size() == maxSize) {
            wait();
        }
        storage.add(new Object());
        System.out.println("生产:" + storage.get(0));
        notifyAll();
    }

    public synchronized void take() throws InterruptedException {
        while (storage.size() == 0) {
            wait();
        }
        System.out.println("消费:" + storage.remove());
        notifyAll();
    }

    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue x = new MyBlockingQueue(2);

        Runnable producer = ()->{
            try {
                x.put();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        Runnable consumer = ()->{
            try {
                x.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        new Thread(producer).start();
        new Thread(producer).start();
        new Thread(consumer).start();

    }
}
